module Pictopus
  class CommandLineError < StandardError; end
  
  class << self
    def default_options
      @options ||= {
        :command_path => nil,
        :log => true,
        :swallow_stderr => true,
        :log_command => true
      }
    end
    
    def run(cmd, params="", options = {})
      options[:expected_outcodes] ||= 0
      command = %Q[#{path_for_command(cmd)} #{params}].gsub(/\s+/, " ")
      command = "#{command} 2>#{bit_bucket}" if Pictopus.default_options[:swallow_stderr]
      #Rails.logger.info(command) if Pictopus.default_options[:log_command]
      puts command
      output = system(command)
      unless Array(options[:expected_outcodes]).include?($?.exitstatus)
        raise Pictopus::CommandLineError, "Error while running #{cmd}"
      end
    end
    
    def path_for_command(command)
      path = [default_options[:command_path], command].compact!
      File.join(*path)
    end
    
    def bit_bucket #:nodoc:
      File.exists?("/dev/null") ? "/dev/null" : "NUL"
    end
  end
end

require 'pictopus/gradient'